<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <div :class="isMobile ? 'mobile-button-group horizontal' : ''">
        <BaseButton @click="go(-1)">
          {{ t('common.back') }}
        </BaseButton>
        <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
          {{ t('action.save') }}
        </BaseButton>
      </div>
    </template>
    <!--    表单-->
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules as FormRules"
      label-width="130px"
      :class="isMobile ? 'mobile-form' : ''"
    >
      <div :class="isMobile ? 'form-section' : ''">
        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          :label="t('dealerAssetManagement.customer')"
          prop="customer_id"
        >
          <div style="display: flex; align-items: center; gap: 10px">
            <el-input v-model="form.customer_name" clearable disabled style="width: 250px" />
            <el-button size="small" type="primary" @click="handleOpenCustomer"
              >{{ t('dealerAssetManagement.select') }}
            </el-button>
          </div>
        </el-form-item>
      </div>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-t-40px m-b-20px"></div>

      <div :class="isMobile ? 'form-section' : ''">
        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          :label="t('orderReturn.order_id')"
          prop="order_id"
        >
          <div style="display: flex; align-items: center; gap: 10px">
            <el-input v-model="form.order_no" clearable disabled style="width: 250px" />
            <el-button size="small" type="primary" @click="handleOpenOrder"
              >{{ t('orderReturn.selectOrders') }}
            </el-button>
          </div>
        </el-form-item>
      </div>

      <div :class="isMobile ? 'form-section' : ''">
        <div class="my-3">商品信息</div>

        <!-- 移动端商品卡片视图 -->
        <div v-if="isMobile && tableList.length" class="mobile-card">
          <el-card v-for="item in tableList" :key="item.id" class="product-card">
            <template #header>
              <div class="card-header">
                <span class="product-name">{{ item.product_name }}</span>
                <el-checkbox
                  v-model="item.selected"
                  @change="(checked) => handleMobileSelectionChange(checked, item)"
                  :disabled="!item.selected && multipleSelection.length >= 1"
                >
                  选择
                </el-checkbox>
              </div>
            </template>

            <div class="card-content">
              <div class="info-row">
                <span class="label">{{ t('orderReturn.index') }}:</span>
                <span class="value">{{ item.id }}</span>
              </div>

              <div class="info-row">
                <span class="label">{{ t('orderReturn.warehouses_name') }}:</span>
                <span class="value">{{ item.warehouses_name }}</span>
              </div>

              <div class="info-row">
                <span class="label">{{ t('orderReturn.quantity') }}:</span>
                <div class="value">
                  <el-input-number
                    @change="handleChangeReturnNum"
                    v-model="item.quantity"
                    :min="1"
                    :max="item.quantity ? parseInt(item.quantity as string) : 100000"
                    style="width: 100%"
                  />
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 桌面端表格视图 -->
        <el-table
          v-if="!isMobile"
          :data="tableList"
          highlight-current-row
          row-key="id"
          stripe
          border
          show-summary
          :summary-method="getSummaries as any"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" :reserve-selection="true" width="55" />
          <el-table-column
            :label="t('orderReturn.product_name')"
            prop="product_name"
            min-width="200"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="t('orderReturn.quantity')"
            min-width="180"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              <el-input-number
                @change="handleChangeReturnNum"
                v-model="row!.quantity"
                :min="1"
                :max="row!.max_quantity ? parseInt(row!.max_quantity as string) : 100000"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] my-10px"></div>

      <!-- 支付信息表格 -->
      <div :class="isMobile ? 'form-section' : ''">
        <div class="my-3">支付信息</div>

        <!-- 移动端支付信息卡片视图 -->
        <div v-if="isMobile && paymentTableList.length" class="mobile-card">
          <el-card v-for="item in paymentTableList" :key="item.id" class="payment-card">
            <template #header>
              <div class="card-header">
                <span class="payment-title">{{ item.payment_method }}</span>
                <el-checkbox
                  v-model="item.selected"
                  @change="(checked) => handleMobilePaymentSelectionChange(checked, item)"
                  :disabled="!isRowSelectable(item)"
                >
                  选择
                </el-checkbox>
              </div>
            </template>

            <div class="card-content">
              <div class="info-row">
                <span class="label">费用类型:</span>
                <span class="value">{{ item.fee_type }}</span>
              </div>

              <div class="info-row">
                <span class="label">汇款方式:</span>
                <span class="value">{{ item.remittance_method }}</span>
              </div>

              <div class="info-row">
                <span class="label">交易单号:</span>
                <span class="value">{{ item.transaction_number }}</span>
              </div>

              <div class="info-row">
                <span class="label">支付时间:</span>
                <span class="value">{{ item.payment_time }}</span>
              </div>

              <div class="info-row">
                <span class="label">已支付金额:</span>
                <span class="value">{{ item.amount_paid }}</span>
              </div>

              <div class="info-row">
                <span class="label">应支付金额:</span>
                <span class="value">{{ item.amount_payable }}</span>
              </div>

              <div class="info-row">
                <span class="label">退款金额:</span>
                <div class="value">
                  <el-input-number
                    v-model="item.refund_amount"
                    :min="0"
                    :max="parseFloat(item.amount_paid) || 0"
                    :precision="2"
                    :step="0.01"
                    controls-position="right"
                    style="width: 100%"
                    :disabled="item.is_returnorder_payment === 1"
                  />
                </div>
              </div>

              <div class="info-row">
                <span class="label">退款方式:</span>
                <div class="value">
                  <el-select
                    v-model="item.refund_method"
                    placeholder="请选择"
                    style="width: 100%"
                    :disabled="item.is_returnorder_payment === 1"
                  >
                    <el-option
                      v-for="methodItem in refundMethodList"
                      :key="methodItem.value"
                      :label="methodItem.label"
                      :value="methodItem.value"
                    />
                  </el-select>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 桌面端支付信息表格视图 -->
        <el-table
          :key="paymentTableKey"
          ref="paymentTableRef"
          v-if="!isMobile"
          :data="paymentTableList"
          highlight-current-row
          row-key="id"
          stripe
          border
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
          @selection-change="handlePaymentSelectionChange"
        >
          <el-table-column
            type="selection"
            :reserve-selection="false"
            width="55"
            :selectable="isRowSelectable"
          />
          <el-table-column
            label="支付方式"
            prop="payment_method"
            min-width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="费用类型"
            prop="fee_type"
            min-width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="汇款方式"
            prop="remittance_method"
            min-width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="交易单号"
            prop="transaction_number"
            min-width="200"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="支付时间"
            prop="payment_time"
            min-width="180"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="已支付金额"
            prop="amount_paid"
            min-width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="应支付金额"
            prop="amount_payable"
            min-width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="退款金额"
            min-width="150"
            :show-overflow-tooltip="true"
            fixed="right"
          >
            <template #default="{ row }">
              <el-input-number
                v-model="row.refund_amount"
                :min="0"
                :max="parseFloat(row.amount_paid) || 0"
                :precision="2"
                :step="0.01"
                controls-position="right"
                style="width: 120px"
                :disabled="row.is_returnorder_payment === 1"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="退款方式"
            min-width="150"
            :show-overflow-tooltip="true"
            fixed="right"
          >
            <template #default="{ row }">
              <el-select
                v-model="row.refund_method"
                placeholder="请选择"
                style="width: 120px"
                :disabled="row.is_returnorder_payment === 1"
              >
                <el-option
                  v-for="item in refundMethodList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] my-10px"></div>

      <div :class="isMobile ? 'form-section' : ''">
        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          :label="t('orderReturn.returnorder_type')"
          prop="returnorder_type"
        >
          <el-select
            v-model="form.returnorder_type"
            :filterable="true"
            :placeholder="t('orderReturn.returnorder_type')"
            :clearable="false"
            @change="handleReturnOrderTypeChange"
          >
            <el-option
              v-for="item in returnTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.value === 3 && multipleSelection.length === 0"
            />
          </el-select>
        </el-form-item>

        <!-- 退货方式选择框 - 仅在退款且退货时显示 -->
        <el-form-item
          v-if="form.returnorder_type === 3"
          :class="isMobile ? 'mobile-item' : ''"
          label="退货方式"
          prop="return_method"
        >
          <el-select
            v-model="form.return_method"
            :filterable="true"
            placeholder="请选择退货方式"
            :clearable="false"
            @change="handleReturnMethodChange"
          >
            <el-option
              v-for="item in returnMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 提货地址 - 仅在退货方式为上门提货时显示 -->
        <el-form-item
          v-if="form.returnorder_type === 3 && form.return_method === 'pickup'"
          :class="isMobile ? 'mobile-item' : ''"
          label="提货地址"
          prop="pickup_address"
        >
          <el-input
            v-model="form.pickup_address"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入提货地址"
          />
        </el-form-item>

        <!-- 物流信息 - 仅在退货方式为客户寄送时显示 -->
        <el-form-item
          v-if="form.returnorder_type === 3 && form.return_method === 'customer_send'"
          :class="isMobile ? 'mobile-item' : ''"
          label="物流单号"
          prop="tracking_number"
        >
          <el-input v-model="form.tracking_number" placeholder="请输入物流单号" />
        </el-form-item>

        <el-form-item
          v-if="form.returnorder_type === 3 && form.return_method === 'customer_send'"
          :class="isMobile ? 'mobile-item' : ''"
          label="物流公司"
          prop="logistics_company"
        >
          <el-input v-model="form.logistics_company" placeholder="请输入物流公司" />
        </el-form-item>

        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          :label="getTotalAmountLabel()"
          prop="total_amount"
        >
          <el-input
            v-model="form.total_amount"
            type="number"
            disabled
            :placeholder="getTotalAmountLabel()"
          />
        </el-form-item>
        <el-form-item
          v-if="form.returnorder_type === 3"
          :class="isMobile ? 'mobile-item' : ''"
          :label="t('orderReturn.return_reason')"
          prop="return_reason"
        >
          <el-select
            v-model="form.return_reason"
            :filterable="true"
            :placeholder="t('orderReturn.return_reason')"
            :clearable="false"
          >
            <el-option
              v-for="item in reasonList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          :label="t('orderReturn.signatory')"
          prop="signatory"
        >
          <el-select
            v-model="form.signatory"
            :filterable="true"
            :placeholder="t('orderReturn.signatory')"
            :clearable="false"
          >
            <el-option
              v-for="item in operatorList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          :label="t('orderReturn.signing_date')"
          prop="signing_date"
        >
          <el-date-picker
            v-model="form.signing_date"
            type="date"
            placeholder="签订时间"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          :label="t('orderReturn.owner')"
          prop="owner"
        >
          <el-select
            v-model="form.owner"
            :filterable="true"
            :placeholder="t('orderReturn.owner')"
            :clearable="false"
          >
            <el-option
              v-for="item in operatorList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          :label="t('orderReturn.partner')"
          prop="partner"
        >
          <el-select
            v-model="form.partner"
            :filterable="true"
            :placeholder="t('orderReturn.partner')"
            :clearable="false"
            multiple
          >
            <el-option
              v-for="item in operatorList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          :label="t('orderReturn.remark')"
          prop="remark"
        >
          <el-input
            v-model="form.remark"
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 15 }"
            :placeholder="t('orderReturn.remark')"
          />
        </el-form-item>

        <!-- 附件上传 -->
        <el-form-item :class="isMobile ? 'mobile-item' : ''" label="附件" prop="attachfiles">
          <UploadFile
            url="/common/uploadFile"
            ref="UploadFileRef"
            class="w-100%"
            drag
            multiple
            :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'word', 'txt']"
            :params="{ directory: 6 }"
            :limit="9"
            upload-file-button-name="点击上传或拖拽到此处上传"
            buttonWidth="100%"
            list-type="text"
            :button-link="true"
            :show-file-list="true"
            @upload-success-res="handleUploadCallback"
          />
          <div class="m-t-3 text-xs text-gray-800">最多上传 9 个文件</div>
        </el-form-item>

        <!-- 退款地址 -->
        <el-form-item
          :class="isMobile ? 'mobile-item' : ''"
          label="退款地址"
          prop="payment_address"
        >
          <el-input
            v-model="form.payment_address"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入退款地址"
          />
        </el-form-item>
      </div>
    </el-form>
  </ContentDetailWrap>
  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="getExposeCustomerData"
  />
  <DialogOrderChecked ref="DialogOrderCheckedRef" @expose-multiple-data="getExposeOrderData" />
</template>

<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElButton, ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  createDataApi,
  getEnumApi,
  getOrderListApi,
  getOrderPaymentListApi,
  getOrderPaymentResourceApi
} from '@/api/orderReturn'
import { getOrderEnumApi } from '@/api/order'
import DialogCustomerChecked from '../../Customer/Customer/components/DialogChecked/index.vue'
import DialogOrderChecked from '@/views/OrderReturn/OrderReturnManage/components/DialogOrderChecked/index.vue'
import UploadFile from '@/components/UploadFile/index.vue'
import { useUserStore } from '@/store/modules/user'
import Decimal from 'decimal.js'
import { useEnumeratePicker } from '@/utils'
import { useAppStore } from '@/store/modules/app'

const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const { t } = useI18n()
const { push, go } = useRouter()
const { query } = useRoute()
const userStore = useUserStore()

const loading = ref<boolean>(false)

const returnTypeList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])
const reasonList = ref<Array<Record<string, any>>>([])

const DialogCustomerCheckedRef = ref<InstanceType<typeof DialogCustomerChecked>>()
const DialogOrderCheckedRef = ref()
const UploadFileRef = ref()

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  returnorder_type: '',
  customer_id: '',
  order_type: '',
  order_id: '',
  signatory: '',
  signing_date: '',
  owner: '',
  partner: '',
  product: [],
  total_amount: '',
  currency: '',
  return_method: '',
  pickup_address: '',
  tracking_number: '',
  logistics_company: '',
  attachfiles: [],
  payment_address: ''
})

const multipleSelection = ref<any[]>([])
const selectionPak = ref<any[]>([])
const tableList = ref<Array<Record<string, any>>>([])

// 支付信息相关数据
const paymentTableList = ref<Array<Record<string, any>>>([])
const paymentSelection = ref<any[]>([])
const paymentTableRef = ref()
const paymentTableKey = ref(0)
const refundMethodList = ref<Array<Record<string, any>>>([])

// 支付信息枚举数据
const paymentResourceData = ref<Record<string, any>>({})

// 退货方式选项（测试数据）
const returnMethodOptions = ref<Array<Record<string, any>>>([])

// 计算支付信息里的退款金额总和（只计算勾选的记录）
const totalRefundAmount = computed(() => {
  return paymentTableList.value.reduce((total, item) => {
    // 检查该记录是否在勾选列表中
    const isSelected = paymentSelection.value.some((selected) => selected.id === item.id)
    if (isSelected) {
      return total + (parseFloat(item.refund_amount) || 0)
    }
    return total
  }, 0)
})

// 监听支付信息变化，更新总金额
watch(
  paymentTableList,
  () => {
    form.value.total_amount = totalRefundAmount.value.toFixed(2)
  },
  { deep: true }
)

// 监听支付信息勾选变化，更新总金额
watch(
  paymentSelection,
  () => {
    form.value.total_amount = totalRefundAmount.value.toFixed(2)
  },
  { deep: true }
)
const rules = ref<FormRules>({
  customer_id: [
    {
      required: true,
      message: t('orderReturn.customerMsg'),
      trigger: 'change'
    }
  ],
  order_type: [
    {
      required: true,
      message: t('orderReturn.orderTypeMsg'),
      trigger: 'change'
    }
  ],
  order_id: [
    {
      required: true,
      message: t('orderReturn.orderMsg'),
      trigger: 'change'
    }
  ],
  returnorder_type: [
    {
      required: true,
      message: t('orderReturn.returnTypeMsg'),
      trigger: 'change'
    }
  ],
  signatory: [
    {
      required: true,
      message: t('orderReturn.signatoryMsg'),
      trigger: 'change'
    }
  ],
  signing_date: [
    {
      required: true,
      message: t('orderReturn.signingDateMsg'),
      trigger: 'change'
    }
  ],
  return_reason: [
    {
      required: true,
      message: t('orderReturn.returnReasonMsg'),
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (form.value.returnorder_type === 3 && !value) {
          callback(new Error(t('orderReturn.returnReasonMsg')))
        } else {
          callback()
        }
      }
    }
  ],
  owner: [
    {
      required: true,
      message: t('orderReturn.ownerMsg'),
      trigger: 'change'
    }
  ],
  total_amount: [
    {
      required: true,
      message: t('orderReturn.totalAmountMsg'),
      trigger: 'change'
    }
  ],
  return_method: [
    {
      required: true,
      message: '请选择退货方式',
      trigger: 'change'
    }
  ]
})
//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  handleChangeReturnNum()
}

//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.customer_id = val[0].id
  form.value.owner = val[0].owner_id
  form.value.partner = val[0].partner
  form.value.customer_name = val[0].cusname
  form.value.order_id = ''
  form.value.order_no = ''
  form.value.order_type = ''
  form.value.currency = ''

  // 清空商品信息
  tableList.value = []
  multipleSelection.value = []
  selectionPak.value = []

  // 清空支付信息
  paymentTableList.value = []
  paymentSelection.value = []

  // 重置总金额
  form.value.total_amount = ''
}

const getExposeOrderData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.order_id = val[0].id
  form.value.order_no = val[0].order_no
  form.value.order_type = val[0].order_type
  form.value.currency = val[0].currency
  // 切换关联订单时，先清空支付信息与勾选状态
  paymentTableList.value = []
  paymentSelection.value = []
  form.value.total_amount = ''

  // 清空商品勾选（商品来源于不同订单）
  multipleSelection.value = []
  selectionPak.value = []

  tableList.value = val[0].item

  // 先确保枚举数据已获取，然后获取订单支付信息
  getOrderPaymentInfoWithEnum(val[0].id)

  // 确保表格选择状态被重置（包括表头半选）
  nextTick(() => {
    try {
      paymentTableRef.value?.clearSelection?.()
    } catch (e) {}
    paymentTableKey.value++
  })
}

const handleOpenOrder = () => {
  // 判断客户id不能为空
  if (!form.value.customer_id) {
    ElMessage.warning(t('orderReturn.customerIdMsg'))
    return
  }
  nextTick(() => {
    DialogOrderCheckedRef!.value!.dialogVisible = true
    DialogOrderCheckedRef!.value!.initialize(
      form.value.order_id ? [{ ...form.value, id: form.value.order_id }] : [],
      form.value.customer_id
    )
  })
}

const handleChangeReturnNum = () => {
  // 总金额现在由支付信息自动计算，不再需要手动计算
  // 如果需要其他逻辑可以在这里添加
}

const handleOpenCustomer = () => {
  nextTick(() => {
    DialogCustomerCheckedRef!.value!.dialogVisible = true
    DialogCustomerCheckedRef!.value!.initialize(
      form.value.user_id ? [{ ...form.value, id: form.value.user_id }] : []
    )
  })
}

//列表合计
const getSummaries = (param: Record<string, any>) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  columns.forEach((column: Record<string, any>, index: number) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'underline', textAlign: 'center' } }, [
        '合计'
      ])
      return
    }
    // 由于移除了原价和实际价格列，现在只有序号、商品名称、仓库名称、数量列
    // 如果需要合计数量，可以在这里添加
  })
  return sums
}

// 支付信息相关方法
const handlePaymentSelectionChange = (val: any[]) => {
  paymentSelection.value = val
}

// 移动端支付信息勾选变化
const handleMobilePaymentSelectionChange = (checked: any, item: any) => {
  if (checked) {
    paymentSelection.value.push(item)
  } else {
    paymentSelection.value = paymentSelection.value.filter((selected) => selected.id !== item.id)
  }
}

// 移动端商品选择处理
const handleMobileSelectionChange = (checked: any, item: any) => {
  if (checked) {
    // 添加到选择列表
    if (!multipleSelection.value.find((selected) => selected.id === item.id)) {
      multipleSelection.value.push(item)
    }
  } else {
    // 从选择列表移除
    const index = multipleSelection.value.findIndex((selected) => selected.id === item.id)
    if (index > -1) {
      multipleSelection.value.splice(index, 1)
    }
  }
  handleChangeReturnNum()
}

// 判断行是否可选
const isRowSelectable = (row: Record<string, any>) => {
  // 当 is_returnorder_payment 为 1 时，该行不可选
  const isReturnPayment = row.is_returnorder_payment === 1 || row.is_returnorder_payment === '1'
  console.log(
    'isRowSelectable 检查:',
    row.id,
    'is_returnorder_payment:',
    row.is_returnorder_payment,
    '类型:',
    typeof row.is_returnorder_payment,
    '结果:',
    !isReturnPayment
  )
  return !isReturnPayment
}

// 获取订单支付信息（带枚举数据确保）
const getOrderPaymentInfoWithEnum = async (orderId: number) => {
  // 如果枚举数据还没有获取到，先获取枚举数据
  if (!paymentResourceData.value.payment_method || !paymentResourceData.value.fee_type) {
    await getPaymentResourceData()
  }

  // 确保退款方式选项已更新
  initRefundMethodList()

  // 然后获取支付信息
  await getOrderPaymentInfo(orderId)
}

// 获取订单支付信息
const getOrderPaymentInfo = async (orderId: number) => {
  try {
    console.log('开始获取订单支付信息，订单ID:', orderId)
    const resp = await getOrderPaymentListApi(orderId)
    console.log('支付信息API响应:', resp)

    if (resp.code === 0 && resp.data) {
      // 将API返回的数据转换为支付信息表格格式
      paymentTableList.value = resp.data.map((item: any, index: number) => {
        const feeType = getFeeTypeName(item.fee_type)
        const transferType = getTransferTypeName(item.transfer_type)

        console.log(`支付记录${index + 1}详细信息:`, {
          original_data: item,
          fee_type: item.fee_type,
          fee_type_name: feeType,
          transfer_type: item.transfer_type,
          transfer_type_name: transferType,
          voucher_code: item.voucher_code,
          pay_time: item.pay_time,
          payment_method_name: item.payment_method_name
        })

        return {
          id: item.id, // 使用API返回的原始支付记录ID
          payment_method: item.payment_method_name || 'Wire Transfer',
          fee_type: feeType,
          remittance_method: transferType,
          transaction_number: item.voucher_code || '', // 使用voucher_code作为交易单号
          payment_time: item.pay_time || '', // 使用pay_time作为支付时间
          amount_paid: item.paid_amount || '0.00',
          amount_payable: item.pay_amount || '0.00',
          refund_amount: parseFloat(item.paid_amount) || 0, // 默认值为已支付金额
          refund_method: item.transfer_type || '', // 默认值为汇款方式
          is_returnorder_payment: item.is_returnorder_payment || 0, // 添加退款状态字段
          payment_id: item.id // 保存原始支付记录ID，用于判断是否勾选
        }
      })
      console.log('支付信息表格数据:', paymentTableList.value)
    } else {
      console.warn('没有支付信息数据，使用默认测试数据')
      // 如果没有支付信息，使用默认测试数据
      initPaymentData()
    }
  } catch (error) {
    console.error('获取支付信息失败:', error)
    // 出错时使用默认测试数据
    initPaymentData()
  }
}

// 获取汇款方式名称
const getTransferTypeName = (transferType: number | null) => {
  if (!transferType) return ''
  if (!paymentResourceData.value.transfer_type) return ''

  const transferTypeItem = paymentResourceData.value.transfer_type.find(
    (item: any) => item.value === transferType
  )
  return transferTypeItem ? transferTypeItem.label : ''
}

// 获取费用类型名称
const getFeeTypeName = (feeType: number | null) => {
  if (!feeType) return ''
  if (!paymentResourceData.value.fee_type) return ''

  // 费用类型匹配枚举中的fee_type
  const feeTypeItem = paymentResourceData.value.fee_type.find((item: any) => item.value === feeType)
  return feeTypeItem ? feeTypeItem.label : ''
}

// 获取总金额标签文字
const getTotalAmountLabel = () => {
  return '退款总金额'
}

// 处理退货方式变化
const handleReturnMethodChange = (value: string) => {
  console.log('退货方式变化:', value)

  // 清空相关字段
  form.value.pickup_address = ''
  form.value.tracking_number = ''
  form.value.logistics_company = ''
}

// 处理退货退款单类型变化
const handleReturnOrderTypeChange = (value: number) => {
  console.log('退货退款单类型变化:', value)

  // 如果不是退款且退货，清空退货相关字段
  if (value !== 3) {
    form.value.return_method = ''
    form.value.pickup_address = ''
    form.value.tracking_number = ''
    form.value.logistics_company = ''
    form.value.return_reason = '' // 清空退货原因
  }

  switch (value) {
    case 1: // 仅退款
      console.log('执行仅退款逻辑')
      // 仅退款：只显示支付信息，不显示商品信息
      // 可以在这里添加相应的UI控制逻辑
      break

    case 2: // 补偿款
      console.log('执行补偿款逻辑')
      // 补偿款：显示支付信息，可能不需要商品信息
      // 可以在这里添加相应的UI控制逻辑
      break

    case 3: // 退款且退货
      console.log('执行退款且退货逻辑')
      // 退款且退货：显示商品信息和支付信息
      // 可以在这里添加相应的UI控制逻辑
      break

    default:
      console.log('未知的退货退款单类型:', value)
      break
  }
}

// 获取支付信息枚举数据
const getPaymentResourceData = async () => {
  try {
    const resp = await getOrderPaymentResourceApi()
    if (resp.code === 0 && resp.data) {
      paymentResourceData.value = resp.data
      console.log('支付信息枚举数据获取成功:', resp.data)
      console.log('枚举数据结构:', {
        payment_method: resp.data.payment_method,
        fee_type: resp.data.fee_type,
        transfer_type: resp.data.transfer_type
      })

      // 获取到枚举数据后，更新退款方式选项
      initRefundMethodList()
    } else {
      console.warn('支付信息枚举数据获取失败:', resp)
    }
  } catch (error) {
    console.error('获取支付信息枚举失败:', error)
  }
}

// 初始化支付信息测试数据
const initPaymentData = () => {
  paymentTableList.value = []
}

// 初始化退款方式选项
const initRefundMethodList = () => {
  // 使用支付信息枚举中的transfer_type作为退款方式选项
  if (paymentResourceData.value.transfer_type) {
    refundMethodList.value = paymentResourceData.value.transfer_type.map((item: any) => ({
      value: item.value,
      label: item.label
    }))
  } else {
    // 如果还没有获取到枚举数据，先设置为空数组
    refundMethodList.value = []
  }
}

// 初始化退货方式选项（测试数据）
const initReturnMethodOptions = () => {
  returnMethodOptions.value = [
    { value: 'pickup', label: '上门提货' },
    { value: 'customer_send', label: '客户寄送' }
  ]
}

// 文件上传回调
const handleUploadCallback = (val: any) => {
  if (!val) return

  if (!form.value.attachfiles) {
    form.value.attachfiles = []
  }

  form.value.attachfiles.push(val)
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      // 只有在退款且退货时才检查商品勾选
      if (form.value.returnorder_type === 3 && !multipleSelection.value.length) {
        return ElMessage.warning('请勾选商品')
      }

      // 检查支付信息是否勾选
      if (!paymentSelection.value.length) {
        return ElMessage.warning('请勾选支付信息')
      }

      // 检查退款金额是否填写
      const hasRefundAmount = paymentTableList.value.some(
        (item) => item.refund_amount && parseFloat(item.refund_amount) > 0
      )
      if (!hasRefundAmount) {
        return ElMessage.warning('请填写退款金额')
      }

      // 检查退款方式是否选择
      const hasRefundMethod = paymentTableList.value.some(
        (item) => item.refund_method && item.refund_method !== ''
      )
      if (!hasRefundMethod) {
        return ElMessage.warning('请选择退款方式')
      }

      // 检查勾选的支付信息是否都填写了退款金额和退款方式
      const selectedPayments = paymentTableList.value.filter((item, index) => {
        return paymentSelection.value.some((selected) => selected.id === item.id)
      })

      const incompletePayments = selectedPayments.filter(
        (item) =>
          !item.refund_amount ||
          parseFloat(item.refund_amount) <= 0 ||
          !item.refund_method ||
          item.refund_method === ''
      )

      if (incompletePayments.length > 0) {
        return ElMessage.warning('请完善勾选的支付信息的退款金额和退款方式')
      }

      // 构建API要求的参数格式
      const apiParams: Record<string, any> = {
        customer_id: Number(form.value.customer_id),
        order_id: form.value.order_id,
        owner: Number(form.value.owner),
        partner: Array.isArray(form.value.partner)
          ? form.value.partner.map((p: any) => Number(p))
          : [],
        returnorder_type: Number(form.value.returnorder_type),
        signatory: Number(form.value.signatory),
        signing_date: form.value.signing_date || '',
        return_reason: Number(form.value.return_reason),
        remark: form.value.remark,
        attachfiles: form.value.attachfiles,
        payment_address: form.value.payment_address,

        // 支付信息 - 只处理已勾选的支付记录
        payment_list: paymentSelection.value.map((item: any) => ({
          id: Number(item.id),
          amount: Number(item.refund_amount || 0),
          transfer_type: Number(item.refund_method || 0),
          notes: null
        }))
      }

      // 只有在退款且退货时才处理商品信息
      if (form.value.returnorder_type === 3) {
        const merge = selectionPak.value.concat(multipleSelection.value)
        // 使用 forEach 方法遍历合并后的数组
        form.value.product = []
        merge.forEach((item: any) => {
          // 将每个对象转换为所需的格式
          const formattedItem = {
            id: item.product_id, // 使用 product_id 而不是 item.id
            quantity: item.quantity
          }
          form.value.product.push(formattedItem)
        })

        // 添加商品信息到API参数
        apiParams.products_list = form.value.product.map((item: any) => ({
          id: Number(item.id),
          return_quantity: Number(item.quantity)
        }))
      } else {
        // 仅退款或补偿款时，商品信息为空数组
        apiParams.products_list = []
      }

      // 条件字段处理
      if (form.value.returnorder_type === 3) {
        apiParams.returnorder_method =
          form.value.return_method === 'pickup'
            ? 1
            : form.value.return_method === 'customer_send'
              ? 2
              : 0

        if (form.value.return_method === 'pickup') {
          apiParams.delivery_address = form.value.pickup_address
        }

        if (form.value.return_method === 'customer_send') {
          apiParams.express_company = form.value.logistics_company
          apiParams.tracking_number = form.value.tracking_number
        }
      }

      // 添加新增字段
      apiParams.attachfiles = form.value.attachfiles
      apiParams.payment_address = form.value.payment_address

      const resp = await createDataApi(apiParams)
      if (resp.code === 0) {
        ElMessage.success(t('orderReturn.createSucMsg'))
        // 提交成功后重置表单数据
        resetFormData()
        push({ path: '/orderReturn-management/orderReturn' })
      }
    }
  })
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  returnTypeList.value = resp.data.returnorder_type
  operatorList.value = resp.data.operator
  reasonList.value = resp.data.return_reason
}
//获取枚举
const optionSet = ref<Record<string, any>>({})
const getDropDownBoxOrderInfo = async () => {
  const resp = await getOrderEnumApi({ field: 'all' })
  optionSet.value = resp.data
}
const routerParams = ref<Record<string, any>>({})
const initData = async () => {
  // 直接从URL参数获取数据
  const order_id = query.order_id
  const order_no = query.order_no
  const customer_id = query.customer_id
  const cusname = query.cusname

  // 填充客户信息
  form.value.customer_id = customer_id
  form.value.customer_name = cusname

  // 填充关联订单信息
  form.value.order_id = order_id
  form.value.order_no = order_no

  // 设置负责人默认值
  form.value.owner = userStore.getUserInfo?.id

  // 获取商品信息和支付信息
  if (query.order_id) {
    await getOrderInfo()
  }
}

// 重置表单数据
const resetFormData = () => {
  form.value = {
    returnorder_type: '',
    customer_id: '',
    order_type: '',
    order_id: '',
    signatory: '',
    signing_date: '',
    owner: '',
    partner: '',
    product: [],
    total_amount: '',
    currency: '',
    return_method: '',
    pickup_address: '',
    tracking_number: '',
    logistics_company: '',
    customer_name: '',
    order_no: '',
    return_reason: '',
    remark: '',
    attachfiles: [],
    payment_address: ''
  }

  // 重置表格数据
  tableList.value = []
  paymentTableList.value = []
  multipleSelection.value = []
  paymentSelection.value = []

  // 重置表单验证状态
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}
//初始化请求
const getOrderInfo = async () => {
  try {
    const params = {
      order_id: query.order_id,
      order_type: 'order'
    }

    const resp = await getOrderListApi(params)

    if (resp?.data?.list && resp.data.list.length) {
      let val = resp.data.list[0]

      // 填充订单类型
      form.value.order_type = val.order_type

      // 渲染商品信息到表格
      if (val.item && Array.isArray(val.item)) {
        tableList.value = val.item.map((item: any) => ({
          ...item,
          return_quantity: item.quantity || 1
        }))
      }

      // 获取订单支付信息
      await getOrderPaymentInfoWithEnum(val.id)
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
  }
}
onMounted(async () => {
  // 先重置表单数据
  resetFormData()

  // 先获取必要的枚举数据
  await getPaymentResourceData()
  initReturnMethodOptions()

  // 然后获取其他枚举数据
  getDropDownBoxInfo()
  getDropDownBoxOrderInfo()

  // 最后处理URL参数和初始化数据
  initData()
})
</script>
<style lang="less" scoped>
/* 移动端样式 - 仅在移动端生效 */
@media (width <= 768px) {
  .mobile-button-group {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .mobile-form {
    .el-form-item {
      margin-bottom: 20px;
    }
  }

  .form-section {
    margin-bottom: 20px;
  }

  .mobile-item {
    .el-form-item__content {
      flex-wrap: wrap;

      .el-form-item__label {
        width: 100%;
        margin-bottom: 5px;
        text-align: left;
      }

      .el-form-item__content {
        width: 100%;
      }
    }
  }

  .mobile-card {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 10px;

    .product-card,
    .payment-card {
      width: 100%;

      .el-card__header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .product-name {
          flex-grow: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .el-card__body {
        padding: 10px;
      }
    }
  }

  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;

    .label {
      font-weight: bold;
      color: #333;
    }

    .value {
      color: #666;
      text-align: right;
      flex-grow: 1;
    }
  }
}

/* 桌面端保持原有样式 */
@media (width >= 769px) {
  .mobile-button-group {
    display: none;
  }

  .mobile-form {
    .el-form-item {
      margin-bottom: inherit;
    }
  }

  .form-section {
    margin-bottom: inherit;
  }

  .mobile-item {
    .el-form-item__content {
      flex-wrap: inherit;

      .el-form-item__label {
        width: inherit;
        margin-bottom: inherit;
        text-align: inherit;
      }

      .el-form-item__content {
        width: inherit;
      }
    }
  }
}
</style>
